package utils

import (
	"crypto/hmac"
	"crypto/sha256"
	"fmt"
	"github.com/wonderivan/logger"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"time"
	xtime "time"
)

func GenerateToken(str string) (token string) {
	h := hmac.New(sha256.New, []byte("2hNYLAaI%MC%CMYn"))
	fstr := fmt.Sprintf("%s_%d", str, time.Now().Unix())
	_, _ = io.WriteString(h, fstr)
	token = fmt.Sprintf("%x", h.Sum(nil))
	return
}

func CreateCaptcha() string {
	return fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
}

func HttpPostFrom(reqUrl string, data url.Values) []byte {
	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.PostForm(reqUrl, data)
	if err != nil {
		logger.Error("HttpPostFrom_Error | err=%+v", err)
		return nil
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	return result
}

func HttpGetFrom(reqUrl string) []byte {
	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(reqUrl)
	if err != nil {
		logger.Error("HttpGetFrom | err=%+v", err)
		return nil
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	return result
}

func GetIDTime() (nowUnixTime int64) {
	loc, _ := time.LoadLocation("Asia/Calcutta")
	t := time.Now()
	nowUnixTime = t.In(loc).Unix()
	return nowUnixTime

}

type Duration xtime.Duration

func (d *Duration) UnmarshalText(text []byte) error {
	tmp, err := xtime.ParseDuration(string(text))
	if err == nil {
		*d = Duration(tmp)
	}
	return err
}
